package com.xwj.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xwj.entity.RaRole;
import com.xwj.entity.SysUserLog;
import com.xwj.entity.UserInfo;
import com.xwj.poi.PoIExcelOutPut;
import com.xwj.service.Impl.RaRoleServiceImpl;
import com.xwj.service.Impl.RaUserServiceImpl;
import com.xwj.service.Impl.SysUserLogServiceImpl;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by thinkjoy on 2017/7/21.
 * 后台用户管理
 */
@RestController
@RequestMapping("/admin/user/")
public class UserController {

    @Autowired
    private RaUserServiceImpl raUserService;
    @Autowired
    private RaRoleServiceImpl raRoleService;
    @Autowired
    private SysUserLogServiceImpl sysUserLogService;

    private int pagesize = 10;

    /**
     * 用户列表
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping("userlist")
    public ModelAndView usermanager(ModelAndView modelAndView, @RequestParam(value = "pageindex", required = false) Integer pageindex) {
        PageInfo<UserInfo> page;
        if (pageindex == null) {
            page = raUserService.findAllUserPage(1, pagesize);
        } else {
            page = raUserService.findAllUserPage(pageindex, pagesize);
        }
        List<UserInfo> userInfos = new ArrayList<>();
        for (UserInfo u : page.getList()) {
            u.setRaRole(raRoleService.findRoleById(u.getRoleid()));
            userInfos.add(u);
        }
        List<RaRole> raRoles = raRoleService.findAllRole();
        modelAndView.addObject("userInfoList", userInfos);
        modelAndView.addObject("raRoles", raRoles);
        modelAndView.addObject("pageindex", page.getPageNum());
        modelAndView.addObject("pagecount", page.getPages());
        modelAndView.setViewName("/admin/user");
        return modelAndView;
    }

    /**
     * 添加单个用户
     *
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "addsingleuser", method = RequestMethod.POST)
    public String addSingleUser(UserInfo userInfo) {
        boolean flag = false;
        List<UserInfo> userInfos = raUserService.findAllUser();
        for (UserInfo u : userInfos) {
            if (u.getAccountid().equals(userInfo.getAccountid())) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            String slat = UUID.randomUUID().toString().substring(0, 8);
            String spwd = new Md5Hash(userInfo.getPassword(), slat).toString();
            userInfo.setPassword(spwd);
            userInfo.setSalt(slat);
            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            userInfo.setCreatetime(bartDateFormat.format(date));
            int row = raUserService.addSingleUser(userInfo);
            if (row > 0) {
                return "0";
            } else {
                return "1";
            }
        } else {
            return "2";
        }
    }

    /**
     * 上传excel文件
     */
    @RequestMapping(value = "uploadExcel", method = RequestMethod.POST)
    public String uploadExcel(@RequestParam("uploadexcel") MultipartFile file, HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String localPathDir = "/files";
        String localRealPathDir = request.getSession().getServletContext()
                .getRealPath(localPathDir);
        File logoSaveFile = new File(localRealPathDir);
        if (!logoSaveFile.exists())
            logoSaveFile.mkdirs();
        /** 页面控件的文件流* */
        MultipartFile multipartFile = multipartRequest.getFile("uploadexcel");
        String fileName = localRealPathDir + File.separator + file.getOriginalFilename();
        File files = new File(fileName);
        multipartFile.transferTo(files);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "0");
        jsonObject.put("name", file.getOriginalFilename());
        jsonObject.put("path", fileName);
        return jsonObject.toJSONString();
    }

    /**
     * 批量导入用户
     * 读取excel并导入数据库
     *
     * @param filepath
     * @return
     */
    @RequestMapping(value = "addmuluser", method = RequestMethod.POST)
    public String addmuluser(@RequestParam("filepath") String filepath) {
        List<UserInfo> users = raUserService.findAllUser();
        try {
            PoIExcelOutPut poIExcelOutPut = new PoIExcelOutPut(filepath);
            List<UserInfo> userInfoList = poIExcelOutPut.loadNoticeInfo();
            List<UserInfo> userInfos = new ArrayList<>();
            List<String> repeatid = new ArrayList<>();
            if (userInfoList.size() > 0) {
                for (UserInfo u : userInfoList) {

                    for (int i = 0; i < users.size(); i++) {
                        if (u.getAccountid().equals(users.get(i).getAccountid())) {
                            repeatid.add(u.getAccountid());
                            break;
                        }
                    }
                    String salt = UUID.randomUUID().toString().substring(0, 8);
                    if (StringUtils.isEmpty(u.getPassword())) {
                        u.setPassword(new Md5Hash(u.getAccountid(), salt).toString());
                    } else {
                        u.setPassword(new Md5Hash(u.getPassword(), salt).toString());
                    }
                    if (StringUtils.isEmpty(u.getPhoto())) {
                        u.setPhoto("/static/image/photo.jpg");
                    }
                    u.setSalt(salt);
                    u.setRoleid(2);
                    SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    u.setCreatetime(bartDateFormat.format(date));
                    userInfos.add(u);
                }
                if (repeatid.size() > 0) {
                    return JSON.toJSONString(repeatid);
                } else {
                    raUserService.addMulUser(userInfos);
                    return "0";
                }
            } else {
                return "1";
            }
        } catch (IOException e) {
            e.printStackTrace();
            File files = new File(filepath);
            files.delete();
            return "2";
        } finally {
            File files = new File(filepath);
            files.delete();
        }
    }


    /**
     * 删除用户
     *
     * @param accountid
     * @return
     */
    @RequestMapping("deluser")
    public String delUser(String accountid) {
        int row = raUserService.delUserByAccountid(accountid);
        if (row > 0) {
            return "0";
        } else {
            return "1";
        }
    }

    /**
     * 冻结/解冻用户
     *
     * @param accountid
     * @param delflag
     * @return
     */
    @RequestMapping("frozenuser")
    public String frozenuser(String accountid, String delflag) {
        int row = raUserService.updateDelfalgByAccountid(accountid, delflag);
        if (row > 0) {
            if (delflag.equals("0")) {
                return "0";
            } else {
                return "1";
            }
        } else {
            if (delflag.equals("0")) {
                return "2";
            } else if (delflag.equals("1")) {
                return "3";
            }
        }
        return "";
    }

    /**
     * 用户详情
     *
     * @param accountid
     * @return
     */
    @RequestMapping("detail")
    public Map<String, Object> userdetail(@RequestParam("accountid") String accountid) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = raUserService.findPropertyByAccountID(accountid);
        List<RaRole> raRoles = raRoleService.findAllRole();
        List<SysUserLog> sysUserLogs = sysUserLogService.findAllUserLogByAccountid(accountid);
        map.put("userInfo", userInfo);
        map.put("raRoles", raRoles);
        map.put("sysUserLogs", sysUserLogs);
        return map;
    }

    /**
     * 用户详情修改密码
     *
     * @param password
     * @param accountid
     * @return
     */
    @RequestMapping(value = "detail/updatepwd", method = RequestMethod.POST)
    public String updatepwd(@RequestParam("password") String password, @RequestParam("accountid") String accountid) {
        String slat = UUID.randomUUID().toString().substring(0, 8);
        String spwd = new Md5Hash(password, slat).toString();
        UserInfo userInfo = new UserInfo();
        userInfo.setAccountid(accountid);
        userInfo.setSalt(slat);
        userInfo.setPassword(spwd);
        if (raUserService.updatepwd(userInfo) > 0) {
            return "0";
        } else {
            return "1";
        }
    }
}
